package com.example.start.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.start.common.CommonResp;
import com.example.start.common.PageResp;
import com.example.start.entity.User;
import com.example.start.mapper.UserMapper;
import com.example.start.req.UserReq;
import com.example.start.req.UserSaveReq;
import com.example.start.service.UserService;
import com.example.start.utils.CopyUtil;
import com.example.start.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Random;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {


    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;


    @Override
    public PageResp<User> getList(UserReq userReq) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(userReq.getName())){
            queryWrapper.lambda().eq(User::getName,userReq.getName());
        }
        if(!ObjectUtils.isEmpty(userReq.getPhone())){
            queryWrapper.lambda().eq(User::getPhone,userReq.getPhone());
        }
        if(!ObjectUtils.isEmpty(userReq.getCity())){
            queryWrapper.lambda().eq(User::getCity,userReq.getCity());
        }
        Page<User> page = new Page<>(userReq.getPage(), userReq.getSize());
        IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
        PageResp<User> pageResp = new PageResp<>();
        pageResp.setTotal(userIPage.getTotal());
        pageResp.setList(userIPage.getRecords());


        return pageResp;
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public void save(UserSaveReq userSaveReq) {
        User entity = CopyUtil.copy(userSaveReq,User.class);
        if(ObjectUtils.isEmpty(userSaveReq.getId())){
            entity.setId(snowFlake.nextId());
            userMapper.insert(entity);
        }else{
            userMapper.updateById(entity);
        }

    }


}
